//
//  WeatherViewController.m
//  WeatherOFChangsha
//
//  Created by zkingsoft on 15/12/15.
//  Copyright (c) 2015年 zkingsoft. All rights reserved.
//

#import "WeatherViewController.h"

#import "ChooseCityViewController.h"

@interface WeatherViewController (){
    MBProgressHUD       *HUD;
}
@end

@implementation WeatherViewController

#pragma mark - 监控网络是否连接
- (void)reachability{
    // 检测网络连接状态
    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
    // 连接状态回调处理
    /* AFNetworking的Block内使用self须改为weakSelf, 避免循环强引用, 无法释放 */
    __weak typeof(self) weakSelf = self;
    [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status)
     {
         switch (status)
         {
             case AFNetworkReachabilityStatusUnknown:
                 // 回调处理
                 break;
             case AFNetworkReachabilityStatusNotReachable:
                 // 回调处理 没有网络 添加一个通知
                 [[NSNotificationCenter defaultCenter] postNotificationName:@"NOTREACHABLE" object:weakSelf];
                 break;
             case AFNetworkReachabilityStatusReachableViaWWAN:
                 // 回调处理
                 break;
             case AFNetworkReachabilityStatusReachableViaWiFi:
                 // 回调处理
                 break;
             default:
                 break;
         }
     }];
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    
    NSString *cityNameString = [[NSUserDefaults standardUserDefaults] objectForKey:@"cityName"];
    if ([cityNameString isEqual:[NSNull null]]&&cityNameString == nil) {
        self.cityName = @"长沙市";
    }else{
        self.cityName = cityNameString;
    }
    
    [self SetUpRefresh];
    [self.tableView reloadData];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self reachability];
    _headView = [[WeaherHeaderView alloc] init];
    _weatherModel = [[WeatherModel alloc] init];
    _weatherDataDictionary = [[NSMutableDictionary alloc] init];
    
    NSString *cityNameString = [[NSUserDefaults standardUserDefaults] objectForKey:@"cityName"];
    if ([cityNameString isEqual:[NSNull null]]&&cityNameString == nil) {
        self.cityName = @"长沙市";
    }else{
        self.cityName = cityNameString;
    }
   
    // 背景图片
    _backGroundView = [[WeatherView alloc] init];
    self.view = _backGroundView;
    [_backGroundView InitView];

    self.tableView = _backGroundView.tableView;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.rowHeight = 80;
    self.tableView.backgroundColor = [UIColor clearColor];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    // 给按钮添加响应事件
    [self.headView.chioceCityButton addTarget:self action:@selector(ChioceCityButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    
   
    // 进来的时候首先进行调用一次
    [self SetUpRefresh];
     _weatherModel = [[WeatherModel alloc] initWithDictionary:_weatherDataDictionary];
    [self.tableView reloadData];
    
    // 上啦刷新
    __weak WeatherViewController *weakSelf = self;
    [weakSelf.tableView addPullToRefreshWithActionHandler:^{
        [weakSelf SetUpRefresh];
    }];
    
    // 添加通知 监听数据的变化
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(ResevedDataSuccessful:) name:@"REQUESTSUCCESSFUL" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(RecevedDataDefault:) name:@"REQUESTDEFAULT" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(ResevedNotNet:) name:@"NOTREACHABLE" object:nil];
}


#pragma mark - 收到通知的时候调用
- (void)ResevedNotNet:(NSNotification *)noti{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:@"没有网络" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        NSLog(@"点击了确定按钮");
    }];
    [alertController addAction:okAction];
    [self presentViewController:alertController animated:YES completion:nil];
}

- (void)ResevedDataSuccessful:(NSNotification *)noti{
    // 数据请求成功进行展示
    [_weatherDataDictionary setDictionary:[noti.userInfo objectForKey:@"result"]];
    NSLog(@"----%@", _weatherDataDictionary);
    
    _weatherModel = [[WeatherModel alloc] initWithDictionary:_weatherDataDictionary];
    self.headView.cityNameLabel.text = _weatherModel.currentCity;
    NSArray *array = [[[_weatherModel.weather_data objectAtIndex:0] objectForKey:@"date"] componentsSeparatedByString:@"(实时："];
    NSString *cityWeekString = [array objectAtIndex:0];
    NSString *cityTemString = [array objectAtIndex:1];
    self.headView.cityTempLabel.text = [cityTemString substringToIndex:cityTemString.length-1];
    self.headView.cityWeekLabel.text = [NSString stringWithFormat:@"%@  今天", cityWeekString];
    self.headView.cityPM25Label.text = [NSString stringWithFormat:@"PM25:%@", self.weatherModel.pm25];
    [self.tableView reloadData];
    [self tableView:self.tableView viewForHeaderInSection:0];
}

- (void)RecevedDataDefault:(NSNotification *)noti{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:@"请求数据失败" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        NSLog(@"点击了确定按钮");
    }];
    [alertController addAction:okAction];
    [self presentViewController:alertController animated:YES completion:nil];
}

- (void)SetUpRefresh{
    HUD = [[MBProgressHUD alloc] initWithView:self.view];
    [self.view addSubview:HUD];
    HUD.mode = MBProgressHUDModeAnnularDeterminate;
    
    [HUD showAnimated:YES whileExecutingBlock:^{
        // 下拉刷新
        __weak WeatherViewController *weakSelf = self;
        int64_t delayInSeconds = 1.0;
        dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
        dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
            [weakSelf.tableView beginUpdates];
            
            // 请求数据
            [_weatherModel RequestWeatherDataWithCityName:weakSelf.cityName];
            
            [weakSelf.tableView endUpdates];
            [weakSelf.tableView.pullToRefreshView stopAnimating];
        });
        
        float progress = 0.0f;
        while (progress < 1.0f) {
            progress += 0.01f;
            HUD.progress = progress;
            usleep(10000);
        }
    } completionBlock:^{
        [HUD removeFromSuperview];
        HUD = nil;
    }];
    
    
}



- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (_weatherModel.weather_data.count > 0) {
        return _weatherModel.weather_data.count;
    }else{
        return 4;
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    WeatherTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"WeatherTableViewCell"];
    if (!cell) {
        cell = [[WeatherTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"WeatherTableViewCell"];
        cell.backgroundColor = [UIColor clearColor];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    
    if (indexPath.row == 0) {
        cell.weatherWeekLabel.text = [[[_weatherModel.weather_data objectAtIndex:indexPath.row] objectForKey:@"date"] substringToIndex:2];
    }else{
        cell.weatherWeekLabel.text = [[_weatherModel.weather_data objectAtIndex:indexPath.row] objectForKey:@"date"];
    }
    
    NSURL *dayWeatherImage = [NSURL URLWithString:[[_weatherModel.weather_data objectAtIndex:indexPath.row] objectForKey:@"dayPictureUrl"]];
    NSURL *nightPictureUrl = [NSURL URLWithString:[[_weatherModel.weather_data objectAtIndex:indexPath.row] objectForKey:@"nightPictureUrl"]];
    
    
    // 判断当前时间是白天还是黑夜
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"HH"];
    NSString *str = [formatter stringFromDate:[NSDate date]];
    int time = [str intValue];
    if (time>=18||time<=06) {
        [cell.weatherImageView sd_setImageWithURL:nightPictureUrl placeholderImage:[UIImage imageNamed:@"sun.pnpg"]];
    }else{
        [cell.weatherImageView sd_setImageWithURL:dayWeatherImage placeholderImage:[UIImage imageNamed:@"sun.pnpg"]];
    }
    cell.weatherWeekWeatherLabel.text = [[_weatherModel.weather_data objectAtIndex:indexPath.row] objectForKey:@"weather"];
    cell.weatherTempLabel.text = [[_weatherModel.weather_data objectAtIndex:indexPath.row] objectForKey:@"temperature"];
    
    return cell;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return _headView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 216;
}

#pragma mark - 选择城市点击了
- (void)ChioceCityButtonClicked:(UIButton *)sender{
    ChooseCityViewController *chooseCityViewContro = [[ChooseCityViewController alloc] init];
    
    [self presentViewController:chooseCityViewContro animated:YES completion:nil];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
